﻿using System.Linq;
using MvcContrib.Pagination;
using Tools.Domain.Common.Repositories.Contracts;
using Webshop20.Application.DataTransferObjects;
using Webshop20.Application.Queries.Messages;
using Webshop20.Domain.Catalog.Core.Products;
using Webshop20.Domain.Catalog.Factories.Contracts;
using AutoMapper;
using Webshop20.Application.Common;
using Webshop20.Domain.Shared.Products.Core;

namespace Webshop20.Application.Queries.Services
{
    public interface IGetProductsService : IService{}

    public class GetProductsService : ServiceBase, IGetProductsService
    {
        private readonly IRepository<Product> productRepository;
        private readonly IFilterSpecificationFactory<Product> specificationFactory;

        public GetProductsService(IRepository<Product> productRepository, IFilterSpecificationFactory<Product> specificationFactory)
        {
            this.productRepository = productRepository;
            this.specificationFactory = specificationFactory;

        }

        public override ISystemMessage Handle(ISystemMessage request)
        {   
            
            var getProductsRequest = request as GetProductsRequest;
            var getProductsFilterSpecification =
                specificationFactory.CreateSpecification(getProductsRequest);

            var productsByCategory = productRepository
                                        .FindBySpecification(getProductsFilterSpecification)
                                        .OrderBy(
                                                    getProductsRequest.SortField,
                                                    getProductsRequest.OrderByDescending

                                                )
                                        .Select(product => Mapper.Map(product, new ProductDTO()))
                                        .AsPagination(getProductsRequest.Page, getProductsRequest.PageSize);
                                        //.ToPagedList(getProductsRequest.Page, getProductsRequest.PageSize);
                                        

            return new GetProductsResponse(productsByCategory, productsByCategory.AsEnumerable(), productsByCategory.TotalItems, productsByCategory.PageNumber, productsByCategory.PageSize);
        }
    }
}
